package com.daxia.bumall.web.controller;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.daxia.bumall.common.Logs;
import com.daxia.bumall.dto.FileDTO;
import com.daxia.bumall.util.QiniuUtils;
import com.daxia.bumall.util.WebParamUtils;


@Controller
@RequestMapping(value = "/file", produces="text/html;charset=UTF-8")
public class FileController extends BaseController {
    private String dir = "c:/file";
    
    @RequestMapping("manage")
    public String manage(HttpServletRequest request, Map<String, Object> map, boolean upload) throws Exception {
        if (upload) {
            saveFile(request, "file", dir);
            map.put("msg", "上传成功");
        }
        listFiles(map);
        map.put("upload", true);
        return "file/file_manage";
    }
    
    @RequestMapping("webuploader")
    @ResponseBody
    public String webuploader(HttpServletRequest request) throws Exception {
    	String url = "";
    	MultipartHttpServletRequest mhs = (MultipartHttpServletRequest) request;  
    	MultiValueMap<String,MultipartFile> multiValueMap = mhs.getMultiFileMap();
    	Set<String> set = multiValueMap.keySet();
    	for (String key : set) {
			List<MultipartFile> list = multiValueMap.get(key);
			for (MultipartFile mf : list) {
			       if (mf != null && !mf.isEmpty()) {
			           String imgUrl = QiniuUtils.upload(mf.getBytes());
			           url += imgUrl;
			        }
			}
		}
    	// return url;
    	return url.replace(",", "");
    }

    @RequestMapping("list")
    public String list(HttpServletRequest request, Map<String, Object> map) throws Exception {
        listFiles(map);
        return "file/file_manage";
    }

    
    @RequestMapping("download")
    public ResponseEntity<byte[]> download(String fileName) throws Exception {
        Logs.COMMON.debug("input fileName: " + fileName);
        fileName = WebParamUtils.getUTF8Param(fileName);
        Logs.COMMON.debug("utf8 fileName: " + fileName);
        // fileName = URLDecoder.decode(fileName, "utf-8");
        // Logs.COMMON.debug("decode: " + fileName);
        File file = new File(dir + "/" + fileName);

        if (file.exists() && file.isFile()) {
            HttpHeaders headers = new HttpHeaders();    
            fileName=file.getName();  
            Logs.COMMON.debug("filename: " + fileName);
            headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"),"iso-8859-1"));   
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
                                              headers, HttpStatus.OK);    
        }
        return null;
    }
    
    private void saveFile(HttpServletRequest request, String formInputName, String filePath) throws IOException {
        MultipartHttpServletRequest mhs = (MultipartHttpServletRequest) request;  
        MultipartFile mf = mhs.getFile(formInputName);
        
        
        if (mf != null && !mf.isEmpty()) {
            String fileName = mf.getOriginalFilename();
            File path = new File(filePath);
            if (!path.exists()) {
                path.mkdirs();
            }
            File file = new File(filePath + "/" + fileName);
            if (!file.exists()) {
                mf.transferTo(file);
            } else {
                file.delete();
                mf.transferTo(file);
                //throw new BizException("该文件已经存在");
            }
        }
    }

    private void listFiles(Map<String, Object> map) throws UnsupportedEncodingException {
        File[] files = new File(dir).listFiles(new FileFilter() {
            
            @Override
            public boolean accept(File pathname) {
                return pathname.isFile();
            }
        });
        if (files != null) {
            List<FileDTO> fileDTOs = new ArrayList<FileDTO>();
            for (File file : files) {
                FileDTO dto = new FileDTO();
                dto.setName(file.getName());
                dto.setEncodeName(URLEncoder.encode(file.getName(), "utf-8"));
                // dto.setEncodeName(file.getName());
                dto.setPath("");
                long size = file.length();
                String s = null;
                if (size > 1024 * 1024) {
                    s = (size / 1024 / 1024) + "MB"; 
                } else if (size > 1024) {
                    s = (size / 1024) + "KB"; 
                } else {
                    s = "1KB";
                }
                dto.setSize(s);
                fileDTOs.add(dto);
            }
            map.put("files", fileDTOs);
        }
    }

}
